#!/usr/bin/env python3
"""
初始化管理员用户脚本
"""

import sys
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent.parent))

import asyncio
from sqlalchemy.future import select

from app.database.session import get_db
from app.models.user import User
from app.schemas.user import UserCreate


async def init_admin_users():
    """初始化管理员用户"""
    print("正在初始化管理员用户...")

    # 管理员用户数据
    admin_users = [
        {
            "username": "admin",
            "password": "abc@123456",
            "name": "系统管理员",
            "email": "admin@example.com",
            "role": "admin"
        },
        {
            "username": "suadmin",
            "password": "abc@123456",
            "name": "超级管理员",
            "email": "suadmin@example.com",
            "role": "super-admin"
        }
    ]

    # 获取异步数据库会话
    async for db in get_db():
        try:
            for user_data in admin_users:
                # 检查用户是否已存在
                result = await db.execute(
                    select(User).where(User.username == user_data["username"])
                )
                existing_user = result.scalar_one_or_none()
                if existing_user:
                    print(f"用户 {user_data['username']} 已存在，跳过创建")
                    continue

                # 创建用户
                user_schema = UserCreate(**user_data)
                
                # 生成密码哈希
                from app.routes.auth import get_password_hash
                hashed_password = get_password_hash(user_schema.password)
                
                # 使用属性赋值方式创建User对象
                user = User()
                user.username = user_schema.username
                user.password_hash = hashed_password
                user.name = user_schema.name
                user.email = user_schema.email
                user.role = user_schema.role
                user.is_active = True

                db.add(user)  # type: ignore[attr-defined]
                print(f"创建用户: {user_data['username']} ({user_data['role']})")

            await db.commit()
            print("管理员用户初始化完成!")

        except Exception as e:
            await db.rollback()
            print(f"初始化失败: {e}")
            raise


if __name__ == "__main__":
    asyncio.run(init_admin_users())